const {googleGenerateSecret} = require('public-google-validator');
const {PLATFORM_APPID} = require('admin-my-config');
const {generateUuid} = require('public-uuid');

const db=uniCloud.database();
/**
 * 检测当前用户是否已经存在google密钥，如果没有则创建
 */
async function createGoogleValidator(userRecord,clientInfo){
	const {appId} =clientInfo
	if(!PLATFORM_APPID.includes(appId)){
		throw new Error(`该应用不在白名单内，请联系管理员`)
	}
	// 生成google验证期
	const secret = googleGenerateSecret();
	userRecord.google_secret=secret.base32
	userRecord.google_otpauth_url=secret.otpauth_url
	return userRecord
}

function beforeRegister(event) {
	console.log(event)
	const { userRecord, clientInfo } = event

	if (userRecord.role) {
		userRecord.role.push('user')
	} else {
		userRecord.role = ['user']
	}
	userRecord.nickname=``;
	userRecord.mobile=``;
	userRecord.status=0;		//用户为可用状态
	userRecord.username=`wx${generateUuid(8,16)}`;		//微信用户随机生成用户名
	createGoogleValidator(userRecord,clientInfo);
	return userRecord // 务必返回处理后的userRecord
}

function adminBeforeRegister(event){
	console.log(event)
	const { userRecord, clientInfo } = event
	
	userRecord.register_date=+new Date()
	createGoogleValidator(userRecord,clientInfo);
	return userRecord;	// 务必返回处理后的userRecord
}

function adminBeforeUpdate(event){
	console.log(event)
	const { userRecord, clientInfo } = event
	createGoogleValidator(userRecord,clientInfo);
	return userRecord;	// 务必返回处理后的userRecord
}

module.exports = {
	beforeRegister,
	adminBeforeRegister,
	adminBeforeUpdate
}